package cn.jd.filter;

import org.slf4j.LoggerFactory;

import org.slf4j.Logger;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class RequestTimeFilter implements GatewayFilter, Ordered {
    // 创建一个日志打印器
    private static final Logger log= LoggerFactory.getLogger(RequestTimeFilter.class);

    /**
     *
     * @param exchange 网络交换器里面存放的重要请求以及响应属性请求实例和响应实例，类似于上下文
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求的路径
        String path = exchange.getRequest().getURI().getPath();
        // 打印日志
        log.info("RequestTimeFilter path:{}" + path);
        // 写入请求开始时间
        exchange.getAttributes().put("startTime",System.currentTimeMillis());
        // 执行完成
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
